package io.xccit.train.common.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import io.xccit.train.common.enums.BusinessCode;
import io.xccit.train.common.exception.BusinessException;
import io.xccit.train.common.props.TokenConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @author CH_ywx
 * @version 1.0
 * @create 2024/11/9
 * <p>JWT工具类</p>
 */
@Component
public class JwtUtil {
    @Autowired
    private TokenConfigProperties tokenConfigProperties;

    public String getSecret() {
        return tokenConfigProperties.getSecret();
    }

    /**
     * 生成token
     * @param id 用户id
     * @param mobile 用户手机号
     * @return
     */
    public String createToken(Long id,String mobile){
        //签发时间
        DateTime now = DateTime.now();
        //过期时间
        DateTime expTime = now.offsetNew(DateField.HOUR, 24);
        HashMap<String, Object> payload = new HashMap<>();
        payload.put("id",id);
        payload.put("mobile",mobile);
        payload.put(JWTPayload.ISSUED_AT,now);
        payload.put(JWTPayload.EXPIRES_AT,expTime);
        payload.put(JWTPayload.NOT_BEFORE,now);
        return JWTUtil.createToken(payload,getSecret().getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public boolean verify(String token) {
        if (token == null || token.isEmpty()) {
            throw new BusinessException(BusinessCode.INVALID_TOKEN);
        }
        try {
            JWT jwt = JWTUtil.parseToken(token).setKey(getSecret().getBytes(StandardCharsets.UTF_8));
            boolean validate = jwt.validate(0);
            if (!validate) {
                throw new BusinessException(BusinessCode.INVALID_TOKEN);
            }
            return validate;
        } catch (JWTException e) {
            return false;
        }
    }

    /**
     * 获取token中的用户信息
     * @param token
     * @return
     */
    public JSONObject getJsonObject(String token) {
        if (verify(token)){
            JWT jwt = JWTUtil.parseToken(token).setKey(getSecret().getBytes(StandardCharsets.UTF_8));
            JSONObject payloads = jwt.getPayloads();
            payloads.remove(JWTPayload.ISSUED_AT);
            payloads.remove(JWTPayload.EXPIRES_AT);
            payloads.remove(JWTPayload.NOT_BEFORE);
            return payloads;
        }
        throw new BusinessException(BusinessCode.MEMBER_TOKEN_EXPIRED);
    }
}
